"""
配置管理器
负责管理三个独立的配置文件：providers.yaml、models.yaml、user_config.yaml
"""

import os
import yaml
from typing import Dict, Any, List, Tuple
from pathlib import Path


class ConfigManager:
    """配置管理器类，管理所有配置文件"""
    
    def __init__(self):
        """初始化配置管理器"""
        self.config_dir = Path(__file__).parent
        self.providers_file = self.config_dir / "providers.yaml"
        self.models_file = self.config_dir / "models.yaml"
        self.user_config_file = self.config_dir / "user_config.yaml"
        self.regions_file = self.config_dir / "regions.yaml"
        
        # 缓存配置数据
        self._providers_config = None
        self._models_config = None
        self._user_config = None
        self._regions_config = None
        
        # 确保配置文件存在
        self._ensure_config_files()
    
    def _ensure_config_files(self):
        """确保所有配置文件都存在"""
        files_to_check = [
            self.providers_file,
            self.models_file,
            self.user_config_file,
            self.regions_file
        ]
        
        for file_path in files_to_check:
            if not file_path.exists():
                print(f"警告: 配置文件 {file_path} 不存在")
    
    def _load_yaml(self, file_path: Path) -> Dict[str, Any]:
        """加载YAML文件"""
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                return yaml.safe_load(f) or {}
        except FileNotFoundError:
            print(f"配置文件不存在: {file_path}")
            return {}
        except yaml.YAMLError as e:
            print(f"解析YAML文件失败 {file_path}: {e}")
            return {}
    
    def _save_yaml(self, file_path: Path, data: Dict[str, Any]):
        """保存YAML文件"""
        try:
            with open(file_path, 'w', encoding='utf-8') as f:
                yaml.dump(data, f, default_flow_style=False, allow_unicode=True)
        except Exception as e:
            print(f"保存配置文件失败 {file_path}: {e}")
            raise
    
    def get_providers(self) -> Dict[str, Any]:
        """获取提供商配置"""
        if self._providers_config is None:
            self._providers_config = self._load_yaml(self.providers_file)
        return self._providers_config
    
    def get_regions(self) -> Dict[str, Any]:
        """获取地区配置"""
        if self._regions_config is None:
            self._regions_config = self._load_yaml(self.regions_file)
        return self._regions_config.get('regions', {})
    
    def get_models(self) -> Dict[str, Any]:
        """获取模型详细信息"""
        if self._models_config is None:
            self._models_config = self._load_yaml(self.models_file)
        return self._models_config
    
    def get_user_config(self) -> Dict[str, Any]:
        """获取用户配置"""
        if self._user_config is None:
            self._user_config = self._load_yaml(self.user_config_file)
        return self._user_config
    
    def save_user_config(self, config: Dict[str, Any]):
        """保存用户配置"""
        self._user_config = config
        self._save_yaml(self.user_config_file, config)
    
    def get_available_providers(self) -> List[str]:
        """获取所有可用提供商列表"""
        providers = self.get_providers()
        return list(providers.keys())
    
    def get_providers_by_region(self, region: str) -> List[str]:
        """根据地区获取提供商列表"""
        providers = self.get_providers()
        return [name for name, config in providers.items() 
                if config.get('region') == region]
    
    def get_region_display_name(self, region_code: str) -> str:
        """获取地区显示名称"""
        regions = self.get_regions()
        region_config = regions.get(region_code, {})
        return region_config.get('name', region_code)
    
    def get_available_regions(self) -> List[str]:
        """获取所有可用地区代码"""
        regions = self.get_regions()
        return list(regions.keys())
    
    def get_provider_models(self, provider: str) -> List[str]:
        """获取指定提供商的模型列表"""
        providers = self.get_providers()
        if provider in providers:
            return providers[provider].get('models', [])
        return []
    
    def get_model_info(self, provider: str, model: str) -> Dict[str, Any]:
        """获取模型详细信息"""
        models = self.get_models()
        if provider in models and model in models[provider]:
            return models[provider][model]
        return {}
    
    def get_provider_config(self, provider: str) -> Dict[str, Any]:
        """获取提供商配置"""
        providers = self.get_providers()
        return providers.get(provider, {})
    
    def update_api_key(self, provider: str, api_key: str):
        """更新API密钥"""
        user_config = self.get_user_config()
        if 'api_keys' not in user_config:
            user_config['api_keys'] = {}
        user_config['api_keys'][provider] = api_key
        self.save_user_config(user_config)
    
    def get_api_key(self, provider: str) -> str:
        """获取指定提供商的API密钥"""
        user_config = self.get_user_config()
        return user_config.get('api_keys', {}).get(provider, "")
    
    def set_current_provider_model(self, provider: str, model: str):
        """设置当前提供商和模型"""
        user_config = self.get_user_config()
        user_config['provider'] = provider
        user_config['model'] = model
        self.save_user_config(user_config)
    
    def get_current_provider_model(self) -> Tuple[str, str]:
        """获取当前提供商和模型"""
        user_config = self.get_user_config()
        provider = user_config.get('provider', '')
        model = user_config.get('model', '')
        return provider, model
    
    def get_export_formats(self) -> Dict[str, bool]:
        """获取CAD导出格式配置"""
        user_config = self.get_user_config()
        return user_config.get('export_formats', {})
    
    def update_export_formats(self, formats: Dict[str, bool]):
        """更新导出格式配置"""
        user_config = self.get_user_config()
        user_config['export_formats'] = formats
        self.save_user_config(user_config)
    
    def is_configured(self) -> bool:
        """检查是否已配置API密钥"""
        provider, model = self.get_current_provider_model()
        if not provider or not model:
            return False
        
        api_key = self.get_api_key(provider)
        return bool(api_key.strip())
    
    def get_current_model_config(self) -> Dict[str, Any]:
        """获取当前模型的完整配置"""
        provider, model = self.get_current_provider_model()
        if not provider or not model:
            return {}
        
        provider_config = self.get_provider_config(provider)
        model_info = self.get_model_info(provider, model)
        api_key = self.get_api_key(provider)
        
        return {
            'provider': provider,
            'model': model,
            'api_key': api_key,
            'base_url': provider_config.get('base_url', ''),
            'timeout': provider_config.get('timeout', 30),
            'headers': provider_config.get('headers', {}),
            'model_info': model_info
        }
    
    def get_model_config(self, provider: str, model: str) -> Dict[str, Any]:
        """获取指定模型的配置信息"""
        provider_config = self.get_provider_config(provider)
        model_info = self.get_model_info(provider, model)
        
        if not provider_config or not model_info:
            return {}
        
        return {
            'provider': provider,
            'model': model,
            'base_url': provider_config.get('base_url', ''),
            'timeout': provider_config.get('timeout', 30),
            'headers': provider_config.get('headers', {}),
            'model_info': model_info
        }
    
    def get_current_config(self) -> Dict[str, Any]:
        """获取当前配置（兼容旧接口）"""
        return self.get_current_model_config()


# 全局配置管理器实例
_config_manager = None


def get_config_manager() -> ConfigManager:
    """获取全局配置管理器实例"""
    global _config_manager
    if _config_manager is None:
        _config_manager = ConfigManager()
    return _config_manager


# 便捷函数
def get_available_providers() -> List[str]:
    """获取所有可用提供商"""
    return get_config_manager().get_available_providers()


def get_provider_models(provider: str) -> List[str]:
    """获取提供商的模型列表"""
    return get_config_manager().get_provider_models(provider)


def get_model_info(provider: str, model: str) -> Dict[str, Any]:
    """获取模型详细信息"""
    return get_config_manager().get_model_info(provider, model)


def update_user_config(provider: str, model: str, api_key: str):
    """更新用户配置"""
    manager = get_config_manager()
    manager.set_current_provider_model(provider, model)
    manager.update_api_key(provider, api_key)


def get_current_config() -> Dict[str, Any]:
    """获取当前配置"""
    return get_config_manager().get_current_model_config()


def get_export_formats() -> Dict[str, bool]:
    """获取导出格式配置"""
    return get_config_manager().get_export_formats()


def update_export_formats(formats: Dict[str, bool]):
    """更新导出格式配置"""
    get_config_manager().update_export_formats(formats)